#!/bin/bash

set -o pipefail

run() {
  # Known issue: stderr is redirected to stdout
  TERM=xterm unbuffer "$@"
  exit_code=$?
  # Ensure output ends with the delimiter expected by "read"
  echo -ne '\r'
  return $exit_code
}

drop_before_cr() {
  result=""
  # split by '\r'
  while read -r -d $'\r' line; do
    # save the last non-empty line only
    test -n "$line" && result="$line"
  done
  # Drop "ESC[K" at the end of line
  escseq=$'\E[K'
  echo "${result%$escseq}"
}

run "$@" | drop_before_cr
